package com.lagou.config;

import com.lagou.enums.SqlCommandType;
import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Locale;

/**
 * @ClassName: XMLMapperBuilder
 * @Auther: Jerry
 * @Date: 2020/6/20 8:32
 * @Desctiption: TODO
 * @Version: 1.0
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(String path) throws DocumentException {
        // 拿到mapper文件输入流
        InputStream inputStream = Resources.getResourcesAsStream(path);
        // 解析mapper文件
        Document document = new SAXReader().read(inputStream);
        Element root = document.getRootElement();
        // 获取mapper结点下的标签
        List<Element> mapperList = root.selectNodes("//select | //insert | //update | //delete");
        String namespace = root.attributeValue("namespace");
        for (Element element : mapperList) {
            // 获取该节点名称
            String name = element.getName();
            // 将该节点类型存放到MappedStatement对象中
            SqlCommandType sqlCommandType = SqlCommandType.valueOf(name.toUpperCase(Locale.ENGLISH));

            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamerType(paramterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setSqlCommandType(sqlCommandType);

            String mappedStatementId = namespace + "." + id;
            // 把mappedStatement存放到map容器中
            configuration.getMappedStatementMap().put(mappedStatementId, mappedStatement);
        }

    }
}
